package com.fjwt.gz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.constants.ApiCodeEnum;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.CouponAwardBo;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.dto.ActivityAwardDTO;
import com.fjwt.gz.db.dto.AwardCouponDTO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.dto.PointDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.*;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.mapper.ActivityMapper;
import com.fjwt.gz.service.mapper.AgentEmployeeMapper;
import com.fjwt.gz.service.mapper.AwardCouponMapper;
import com.fjwt.gz.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 卡券活动信息表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AwardCouponService extends ServiceImpl<AwardCouponMapper, AwardCouponEntity> {

    @Autowired
    private AwardCouponMapper awardCouponMapper;
    @Autowired
    private AwardMchService awardMchService;
    @Autowired
    private AwardAgentService awardAgentService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private AwardSettingService awardSettingService;
    @Autowired
    private PayAuthService payAuthService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private AwardGoodsService awardGoodsService;
    @Autowired
    private AwardVirtualService awardVirtualService;
    @Autowired
    private AwardVirtualInsideService awardVirtualInsideService;
    @Autowired
    private ScoreRecordTotalService scoreRecordTotalService;
    @Autowired
    private MchInfoService mchInfoService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private FansAgentService fansAgentService;
    @Autowired
    private FansUserService fansUserService;
    @Autowired
    private FansActivityService fansActivityService;
    @Autowired
    private FansService fansService;
    @Autowired
    private SendAwardService sendAwardService;
    @Autowired
    private AgentEmployeeService agentEmployeeService;
    @Autowired
    private AgentEmployeeMapper agentEmployeeMapper;


    /**
     * 获取卡券列表
     */
    public IPage<AwardCouponVO> queryList(IPage iPage, AwardCouponDTO awardCouponDTO) {
        if (ObjectUtils.isNotEmpty(awardCouponDTO.getAgentNo())) {
            awardCouponDTO.setAgentNoList(agentInfoService.queryAllSubAgentNo(awardCouponDTO.getAgentNo()));
            awardCouponDTO.setAgentNo(null);
        }
        IPage<AwardCouponVO> page = baseMapper.queryList(iPage, awardCouponDTO);
        if (ObjectUtils.isNotEmpty(page) && ObjectUtils.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(item -> {
                AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(item.getAgentNo());
                if (ObjectUtils.isNotEmpty(agentInfo)) {
                    item.setAgentName(agentInfo.getAgentName());
                }
            });
        }
        return page;
    }

    /**
     * 查询已结束卡券的支付通道
     *
     * @param page
     * @return
     */
    public IPage<CouponAwardBo> selectOverAwardPayAuth(Page page) {
        return awardCouponMapper.selectOverAwardPayAuth(page);
    }

    /**
     * 获取未分配活动的卡券奖品列表
     */
    public List<AwardCouponVO> queryList(AwardCouponDTO awardCouponDTO) {
        if (ObjectUtils.isEmpty(awardCouponDTO) || ObjectUtils.isEmpty(awardCouponDTO.getAgentNo())){
            throw new BizException("请选择机构!");
        }
        if (ObjectUtils.isNotEmpty(awardCouponDTO.getAgentNo())) {
            awardCouponDTO.setAgentNoList(agentInfoService.queryAllSubAgentNo(awardCouponDTO.getAgentNo()));
            awardCouponDTO.setAgentNo(null);
        }
        awardCouponDTO.setState(Constants.AWARD_STATE.ONLINE);
        awardCouponDTO.setIsConfigActivity(false);
        awardCouponDTO.setIsOverTime(false);
        return baseMapper.queryList(awardCouponDTO);
    }

    /**
     * 查询卡券详情
     *
     * @param awardCouponDTO
     * @return
     */
    public AwardCouponVO detail(AwardCouponDTO awardCouponDTO) {
        Long couponId = awardCouponDTO.getCouponId();
        if (couponId == null) {
            throw new BizException("请求参数异常，请检查！");
        }
        AwardCouponEntity awardCouponEntity = awardCouponMapper.selectById(couponId);
        if (awardCouponEntity == null) {
            throw new BizException("该记录不存在！");
        }
        // 可核销卡券的商户
        List<AwardMchEntity> awardMchList = awardMchService.queryMchInfoByCouponId(couponId, Constants.AWARD.COUPON);
        // 分配机构数量
        List<AwardAgentEntity> awardAgentList = awardAgentService.getSavedData(couponId, Constants.AWARD.COUPON);
        // 卡券配置信息
        AwardSettingEntity awardSettingEntity = awardSettingService.getOne(AwardSettingEntity.gw()
                .eq(AwardSettingEntity::getAwardId, awardCouponEntity.getCouponId())
                .eq(AwardSettingEntity::getAwardType, Constants.AWARD.COUPON));

        AwardCouponVO awardCouponVO = new AwardCouponVO();
        BeanUtils.copyProperties(awardCouponEntity, awardCouponVO);
        awardCouponVO.setAwardMchList(awardMchList);
        awardCouponVO.setAwardAgentList(awardAgentList);
        awardCouponVO.setAwardSetting(awardSettingEntity);
        awardCouponVO.setThirdParam(awardCouponEntity.getPayConfig());
        if (ObjectUtils.isNotEmpty(awardCouponEntity.getAgentNo())) {
            AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(awardCouponEntity.getAgentNo());
            if (ObjectUtils.isNotEmpty(agentInfo)) {
                awardCouponVO.setAgentName(agentInfo.getAgentName());
            }
        }
        return awardCouponVO;
    }

    /**
     * 新增卡券
     *
     * @param awardCouponDTO
     * @return
     */
    @Transactional
    public AwardCouponVO add(AwardCouponDTO awardCouponDTO) {
        if (ObjectUtils.isEmpty(awardCouponDTO.getCouponName())) {
            throw new BizException("卡券名称不能为空，请检查！");
        }
        if (ObjectUtils.isEmpty(awardCouponDTO.getPayAmount())) {
            throw new BizException("卡券起付金额不能为空，请检查！");
        }
        if (ObjectUtils.isEmpty(awardCouponDTO.getAgentNo())) {
            throw new BizException("请选择所属机构！");
        }
        if (ObjectUtils.isEmpty(awardCouponDTO.getThirdParam())){
            throw new BizException("请输入三方回参！");
        }
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(awardCouponDTO.getAgentNo());
        if (agentInfo == null) {
            throw new BizException("所选机构不存在，请检查！");
        } else {
            awardCouponDTO.setAgentNo1(agentInfo.getAgentNo1());
            awardCouponDTO.setAgentNo2(agentInfo.getAgentNo2());
            awardCouponDTO.setAgentNo3(agentInfo.getAgentNo3());
            awardCouponDTO.setAgentNo4(agentInfo.getAgentNo4());
        }

        if (awardCouponDTO.getState() != null) {
            if (awardCouponDTO.getState() != Constants.AWARD_STATE.DRAFT) {
                if (awardCouponDTO.getCouponAmount() == null
                        || awardCouponDTO.getCouponNum() == null || awardCouponDTO.getStartTime() == null || awardCouponDTO.getEndTime() == null) {
                    throw new BizException("请求参数不全，请检查！");
                }
                if (awardCouponDTO.getState() == Constants.AWARD_STATE.ONLINE) {
                    if (ObjectUtils.isEmpty(awardCouponDTO.getThirdParam())) {
                        throw new BizException("卡券出资方配置信息缺失，请检查！");
                    }
                }
            }
        }
        if (null != awardCouponDTO.getCouponNum() && null != awardCouponDTO.getCouponPrice()) {
            if (awardCouponDTO.getPayAmount() <= awardCouponDTO.getCouponPrice()) {
                throw new BizException("卡券起付金额不能小于卡券面额");
            }
            int num = awardCouponDTO.getCouponNum();
            int price = awardCouponDTO.getCouponPrice();
            awardCouponDTO.setCouponAmount(num * price);
        }
        //后端生成批次号
        awardCouponDTO.setBatchNo(Utils.generateBathNo());
        AwardCouponEntity awardCouponEntity = new AwardCouponEntity();
        BeanUtils.copyProperties(awardCouponDTO, awardCouponEntity);
        awardCouponEntity.setPayConfig(awardCouponDTO.getThirdParam());

        awardCouponMapper.insert(awardCouponEntity);

        AwardCouponVO awardCouponVO = new AwardCouponVO();
        BeanUtils.copyProperties(awardCouponEntity, awardCouponVO);

        return awardCouponVO;
    }

    /**
     * 修改卡券
     *
     * @param awardCouponDTO
     * @return
     */
    @Transactional
    public void update(AwardCouponDTO awardCouponDTO) {
        if (awardCouponDTO.getCouponId() == null || ObjectUtils.isEmpty(awardCouponDTO.getCouponName()) || ObjectUtils.isEmpty(awardCouponDTO.getAgentNo())) {
            throw new BizException("请求参数异常，请检查！");
        }
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(awardCouponDTO.getAgentNo());
        if (agentInfo == null) {
            throw new BizException("所选机构不存在，请检查！");
        } else {
            awardCouponDTO.setAgentNo1(agentInfo.getAgentNo1());
            awardCouponDTO.setAgentNo2(agentInfo.getAgentNo2());
            awardCouponDTO.setAgentNo3(agentInfo.getAgentNo3());
            awardCouponDTO.setAgentNo4(agentInfo.getAgentNo4());
        }
        AwardCouponEntity awardCouponEntity = awardCouponMapper.selectById(awardCouponDTO.getCouponId());
        if (awardCouponEntity == null) {
            throw new BizException("该记录不存在！");
        }
        if (awardCouponEntity.getState() == Constants.AWARD_STATE.EXPIRED) {
            throw new BizException("该状态不允许修改！");
        }
        // 非草稿状态下只可增加数量
        if (awardCouponEntity.getState() != Constants.AWARD_STATE.DRAFT) {
            if (awardCouponEntity.getCouponNum() > awardCouponDTO.getCouponNum()) {
                throw new BizException("卡券数量不可小于原数量！");
            }
        }
        if (awardCouponEntity.getState() != Constants.AWARD_STATE.ONLINE && awardCouponDTO.getState() == Constants.AWARD_STATE.ONLINE) {
            if (ObjectUtils.isEmpty(awardCouponDTO.getThirdParam())) {
                throw new BizException("卡券出资方配置信息缺失，请检查！");
            }
        }
        awardCouponDTO.setVersion(null);
        BeanUtils.copyProperties(awardCouponDTO, awardCouponEntity);
        int num = awardCouponDTO.getCouponNum();
        int price = awardCouponDTO.getCouponPrice();
        awardCouponEntity.setCouponAmount(num * price);

        awardCouponEntity.setCreatedAt(null);
        awardCouponEntity.setCreatedUid(null);
        awardCouponEntity.setBatchNo(null);

        awardCouponEntity.setPayConfig(awardCouponDTO.getThirdParam());

        awardCouponMapper.updateById(awardCouponEntity);
    }




    /**
     * 修改卡券状态
     *
     * @param awardCouponDTO
     * @return
     */
    public void updateState(AwardCouponDTO awardCouponDTO) {
        Long couponId = awardCouponDTO.getCouponId();
        Integer state = awardCouponDTO.getState();
        if (couponId == null || state == null) {
            throw new BizException("请求参数异常，请检查！");
        }
        AwardCouponEntity awardCouponEntity = awardCouponMapper.selectById(couponId);
        if (awardCouponEntity == null) {
            throw new BizException("该记录不存在！");
        }
        awardCouponEntity.setState(state);
        awardCouponMapper.updateById(awardCouponEntity);
    }

    /**
     * 修改卡券状态为草稿状态
     *
     * @param awardCouponDTO
     * @return
     */
    public void updateCouponStateToDraft(AwardCouponDTO awardCouponDTO) {
        Long couponId = awardCouponDTO.getCouponId();
        if (couponId == null) {
            throw new BizException("请求参数异常，请检查！");
        }
        AwardCouponEntity awardCouponEntity = awardCouponMapper.selectById(couponId);
        if (awardCouponEntity == null) {
            throw new BizException("该记录不存在！");
        }
        long count = activityAwardService.count(ActivityAwardEntity.gw().eq(ActivityAwardEntity::getAwardId, couponId).eq(ActivityAwardEntity::getAwardType, Constants.AWARD.COUPON));
        if (count > 0) {
            throw new BizException("该奖品已配置活动，不能修改为草稿状态！");
        }
        //修改为草稿状态
        awardCouponEntity.setState(Constants.AWARD_STATE.DRAFT);
        awardCouponMapper.updateById(awardCouponEntity);
    }

    /**
     * 删除卡券以及相关联表
     *
     * @param awardCouponDTO
     * @return
     */
    @Transactional
    public void delete(AwardCouponDTO awardCouponDTO) {
        Long couponId = awardCouponDTO.getCouponId();
        if (couponId == null) {
            throw new BizException("请求参数异常，请检查！");
        }
        AwardCouponEntity awardCouponEntity = getById(couponId);
        if (awardCouponEntity == null) {
            throw new BizException("该记录不存在！");
        }
        long count = activityAwardService.count(ActivityAwardEntity.gw().eq(ActivityAwardEntity::getAwardId, couponId).eq(ActivityAwardEntity::getAwardType, Constants.AWARD.COUPON));
        if (count > 0) {
            throw new BizException("该奖品已配置活动，不能删除！");
        }
        boolean couponRemove = removeById(couponId);
        log.info("卡券couponId:{},主表删除couponRemove:{}", couponId, couponRemove);

        LambdaQueryWrapper<AwardMchEntity> awardMchWrapper = new LambdaQueryWrapper<>();
        awardMchWrapper.eq(AwardMchEntity::getAwardId, couponId);
        awardMchWrapper.eq(AwardMchEntity::getAwardType, Constants.AWARD.COUPON);
        boolean awardMchRemove = awardMchService.remove(awardMchWrapper);
        log.info("卡券couponId:{},可核销商户表删除awardMchRemove:{}", couponId, awardMchRemove);

        LambdaQueryWrapper<AwardAgentEntity> awardAgentWrapper = new LambdaQueryWrapper<>();
        awardAgentWrapper.eq(AwardAgentEntity::getAwardId, couponId);
        awardAgentWrapper.eq(AwardAgentEntity::getAwardType, Constants.AWARD.COUPON);
        boolean awardAgentRemove = awardAgentService.remove(awardAgentWrapper);
        log.info("卡券couponId:{},可派发/激活机构表删除awardAgentRemove：{}", couponId, awardAgentRemove);

        // 删除奖品配置信息
        boolean awardSettingRemove = awardSettingService.remove(AwardSettingEntity.gw().eq(AwardSettingEntity::getAwardId, couponId)
                .eq(AwardSettingEntity::getAwardType, Constants.AWARD.COUPON));
        log.info("卡券couponId:{},奖品配置信息表删除awardSettingRemove：{}", couponId, awardSettingRemove);
    }

    /**
     * 随机减券
     * 满减券
     * 新增
     *
     * @param awardCouponDTO
     * @return
     */
    public AwardCouponEntity saveCoupon(AwardCouponDTO awardCouponDTO) {
        if (ObjectUtils.isEmpty(awardCouponDTO.getCouponName())) {
            throw new BizException("卡券名称不能为空，请检查！");
        }
        if (ObjectUtils.isEmpty(awardCouponDTO.getAgentNo())) {
            throw new BizException("请求参数不全，请检查！");
        }
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(awardCouponDTO.getAgentNo());
        if (agentInfo == null) {
            throw new BizException("所选机构不存在，请检查！");
        }
        awardCouponDTO.setAgentNo1(agentInfo.getAgentNo1());
        awardCouponDTO.setAgentNo2(agentInfo.getAgentNo2());
        awardCouponDTO.setAgentNo3(agentInfo.getAgentNo3());
        awardCouponDTO.setAgentNo4(agentInfo.getAgentNo4());
        if(3 == awardCouponDTO.getCouponType()){
            int num = awardCouponDTO.getCouponNum();
            int price = awardCouponDTO.getCouponPrice();
            awardCouponDTO.setCouponAmount(num * price);
        }
        AwardCouponEntity awardCouponEntity = new AwardCouponEntity();
        BeanUtils.copyProperties(awardCouponDTO, awardCouponEntity);

        awardCouponEntity.setBatchNo(Utils.generateBathNo());//后端生成批次号

        awardCouponMapper.insert(awardCouponEntity);
        return awardCouponEntity;
    }

    /**
     * 随机减券
     * 满减券
     * 修改
     *
     * @param awardCouponDTO
     * @return
     */
    public void editCoupon(AwardCouponDTO awardCouponDTO) {
        if (ObjectUtils.isEmpty(awardCouponDTO.getCouponId())) {
            throw new BizException("请求参数异常，请检查！");
        }
        if (ObjectUtils.isEmpty(awardCouponDTO.getCouponName())) {
            throw new BizException("卡券名称不能为空，请检查！");
        }
        if (ObjectUtils.isEmpty(awardCouponDTO.getAgentNo())) {
            throw new BizException("请求参数不全，请检查！");
        }
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(awardCouponDTO.getAgentNo());
        if (agentInfo == null) {
            throw new BizException("所选机构不存在，请检查！");
        }

        AwardCouponEntity awardCouponEntity = awardCouponMapper.selectById(awardCouponDTO.getCouponId());
        awardCouponDTO.setAgentNo1(agentInfo.getAgentNo1());
        awardCouponDTO.setAgentNo2(agentInfo.getAgentNo2());
        awardCouponDTO.setAgentNo3(agentInfo.getAgentNo3());
        awardCouponDTO.setAgentNo4(agentInfo.getAgentNo4());
        if(3 == awardCouponDTO.getCouponType()){
            int num = awardCouponDTO.getCouponNum();
            int price = awardCouponDTO.getCouponPrice();
            awardCouponDTO.setCouponAmount(num * price);
        }
        BeanUtils.copyProperties(awardCouponDTO, awardCouponEntity);
        awardCouponEntity.setCreatedAt(null);
        awardCouponEntity.setCreatedUid(null);
        awardCouponEntity.setBatchNo(null);
        awardCouponMapper.updateById(awardCouponEntity);
    }

    /**获取用户卡券详细信息**/
    public FansCouponsDetailVo getFansCouponDetail (Long couponId, Long goodsId,Long fansAwardId, Long virtualAwardId){
        if(Objects.isNull(couponId) && Objects.isNull(goodsId) && Objects.isNull(virtualAwardId)){
            throw new BizException("请求参数有误");
        }
        FansCouponsDetailVo fansCouponsDetailVo = new FansCouponsDetailVo();
        FansAwardEntity fansAwardEntity = null;
        if (fansAwardId != null) {
            fansAwardEntity = fansAwardService.getById(fansAwardId);
        }
        if (fansAwardEntity != null) {
            fansCouponsDetailVo.setFansAwardId(fansAwardEntity.getFansAwardId());
            fansCouponsDetailVo.setState(fansAwardEntity.getState());
            fansCouponsDetailVo.setOverTime(fansAwardEntity.getOverTime());
        }
        if (couponId !=null){
            AwardCouponEntity couponEntity = awardCouponMapper.selectById(couponId);
            AwardSettingEntity awardSetting = scoreRecordTotalService.findAwardSetting(couponId,Constants.AWARD.COUPON);
            fansCouponsDetailVo.setCouponId(couponId);
            fansCouponsDetailVo.setCouponName(couponEntity.getCouponName());
            fansCouponsDetailVo.setCouponType(couponEntity.getCouponType());
            fansCouponsDetailVo.setSTime(couponEntity.getStartTime());
            fansCouponsDetailVo.setETime(couponEntity.getEndTime());
            fansCouponsDetailVo.setCouponRemark(couponEntity.getRemark());
            fansCouponsDetailVo.setCouponPrice(couponEntity.getCouponPrice());
            fansCouponsDetailVo.setIsNeedActivate(awardSetting.getIsNeedActivate());
            fansCouponsDetailVo.setActivateType(awardSetting.getActivateType());
            fansCouponsDetailVo.setPayAmount(couponEntity.getPayAmount());
            fansCouponsDetailVo.setVerifiedScore(awardSetting.getVerifiedScore());
            fansCouponsDetailVo.setIsOpenReceipt(awardSetting.getIsOpenReceipt());
            fansCouponsDetailVo.setReceiptType(awardSetting.getReceiptType());
            fansCouponsDetailVo.setReceiptContent(awardSetting.getReceiptContent());
        }else if (goodsId !=null){
            AwardGoodsEntity goodsEntity = awardGoodsService.getById(goodsId);
            AwardSettingEntity awardSetting = scoreRecordTotalService.findAwardSetting(goodsId, Constants.AWARD.GOODS);
            fansCouponsDetailVo.setGoodsImgs(goodsEntity.getGoodsImgBanner());
            fansCouponsDetailVo.setGoodsImg(goodsEntity.getGoodsImgListSmall());
            fansCouponsDetailVo.setGoodsName(goodsEntity.getGoodsName());
            fansCouponsDetailVo.setGoodsSku(goodsEntity.getGoodsSku());
            fansCouponsDetailVo.setGoodsId(goodsId);
            fansCouponsDetailVo.setGoodsPrice(goodsEntity.getGoodsPrice());
            fansCouponsDetailVo.setGoosRemark(goodsEntity.getRemark());
            if (fansAwardEntity != null) {
                fansCouponsDetailVo.setWriteTime(fansAwardEntity.getWriteTime());
                fansCouponsDetailVo.setOverTime(fansAwardEntity.getOverTime());
            }else {
                fansCouponsDetailVo.setOverTime(goodsEntity.getGoodsOverTime());
            }
            fansCouponsDetailVo.setIsOpenReceipt(awardSetting.getIsOpenReceipt());
            fansCouponsDetailVo.setReceiptType(awardSetting.getReceiptType());
            fansCouponsDetailVo.setReceiptContent(awardSetting.getReceiptContent());
        }else if (virtualAwardId !=null){
            AwardVirtualEntity virtualAwardEntity = awardVirtualService.getById(virtualAwardId);
            AwardVirtualInsideEntity goodsInsideEntity = awardVirtualInsideService.getById(virtualAwardEntity.getVirtualInsideId());
            AwardSettingEntity awardSetting = scoreRecordTotalService.findAwardSetting(virtualAwardId, Constants.AWARD.VIRTUAL_COUPON);

            fansCouponsDetailVo.setVirtualAwardId(virtualAwardId);
            fansCouponsDetailVo.setGoodsImg(goodsInsideEntity.getGoodsImgListBig());
            fansCouponsDetailVo.setGoodsName(goodsInsideEntity.getGoodsName());
            fansCouponsDetailVo.setGoodsPrice(goodsInsideEntity.getGoodsPrice());
            fansCouponsDetailVo.setGoosRemark(goodsInsideEntity.getGoodsDetail());
            fansCouponsDetailVo.setIsLimitUser(awardSetting.getIsLimitUser());
            fansCouponsDetailVo.setLimitUserContent(awardSetting.getLimitUserContent());
        }
        return fansCouponsDetailVo;
    }

    public List<AwardCouponDTO> selectProcessCopy( Long activityId) {
        LocalDate specificDate = LocalDate.now();
        LocalDateTime startOfDay = specificDate.atStartOfDay();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = startOfDay.format(formatter);
        List<AwardCouponDTO> list = awardCouponMapper.selectProcessCopy(activityId,formattedDate);
        List<AwardCouponDTO> dtos = List.copyOf(list);
        return dtos;
    }

    public CouponVO couponDetail(String mchNo, Long activityId){
        Map map = activityMapper.selectActivitys(String.valueOf(activityId));
        String awardId = map.get("awardId").toString();
        LambdaQueryWrapper<AwardCouponEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AwardCouponEntity::getCouponId,awardId);
        AwardCouponEntity couponAwardEntity = getOne(wrapper);

        LambdaQueryWrapper<AwardSettingEntity> awardSettingWrapper = new LambdaQueryWrapper<>();
        awardSettingWrapper.eq(AwardSettingEntity::getAwardId,awardId);
        awardSettingWrapper.eq(AwardSettingEntity::getAwardType,0);
        AwardSettingEntity awardSettingEntity = awardSettingService.getOne(awardSettingWrapper);
        if (ObjectUtils.isEmpty(couponAwardEntity)){
            throw new BizException("该卡券不存在！");
        }
        CouponVO couponVO = new CouponVO();
        couponVO.setCouponName(couponAwardEntity.getCouponName());
        couponVO.setPayAmount(couponAwardEntity.getPayAmount());
        couponVO.setCouponPrice(couponAwardEntity.getCouponPrice());
        couponVO.setCouponNum(couponAwardEntity.getCouponNum());
        couponVO.setPeriodTimes(awardSettingEntity.getPeriodTimes());
        couponVO.setEveryoneMaxNum(couponAwardEntity.getEveryoneMaxNum());
        couponVO.setStartTime(couponAwardEntity.getStartTime());
        couponVO.setEndTime(couponAwardEntity.getEndTime());
        LambdaQueryWrapper<MchInfoEntity> mcjinfo = new LambdaQueryWrapper<>();
        mcjinfo.eq(MchInfoEntity::getMchNo,mchNo);
        MchInfoEntity mchInfo = mchInfoService.getOne(mcjinfo);

        couponVO.setMchListImage(mchInfo.getMchListImage());
        couponVO.setMchName(mchInfo.getMchName());
        couponVO.setMchNo(mchInfo.getMchNo());
        couponVO.setAgentNo(mchInfo.getAgentNo());
        couponVO.setMcc(mchInfo.getMcc());

        ActivityEntity activityEntity = activityService.getById(activityId);
        couponVO.setActivityImg(activityEntity.getActivityImg());

        return couponVO;
    }

    public IPage<AwardCouponDTO> mchCouponInfo(IPage iPage, Long fansId,Integer state) {
        LambdaQueryWrapper<FansAgentEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FansAgentEntity::getFansId,fansId);
        FansAgentEntity fansAuthEntity = fansAgentService.getOne(wrapper);
        AgentEmployeeEntity agentEmployee = agentEmployeeMapper.selectById(fansAuthEntity.getAgentEmployeeId());
        String agentNo = agentEmployee.getAgentNo();
        AgentInfoEntity agentInfo = agentInfoService.getBaseMapper().selectById(agentNo);
        Integer auditFlowId = null;
        if (ObjectUtil.isEmpty(agentInfo)){
            throw new BizException("未查到商户号");
        }else {
            if (agentInfo.getLevel() == 3){
                auditFlowId = 5;
            }
            if (agentInfo.getLevel() == 2){
                auditFlowId = 4;
            }
        }
        Integer states = null;
        if (state==1){
            states = 0;
        }else {
            states = 1;
        }
        IPage<AwardCouponDTO> awardCouponDTOIPage = null;
        if (agentInfo.getLevel() == 3){
            if (states==1){
                awardCouponDTOIPage = awardCouponMapper.mchCouponInfos(iPage, agentNo, state, states, auditFlowId,3);
            }else {
                awardCouponDTOIPage = awardCouponMapper.mchCouponInfo(iPage, agentNo, state, states, auditFlowId,3);
            }
        }
        if (agentInfo.getLevel() == 2){
            awardCouponDTOIPage = awardCouponMapper.mchCouponInfo(iPage, agentNo, state, states, auditFlowId,2);
        }
        return awardCouponDTOIPage;
    }

    public List<AwardCouponDTO> selectProcess( Long activityId) {
        LocalDate specificDate = LocalDate.now();
        LocalDateTime startOfDay = specificDate.atStartOfDay();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = startOfDay.format(formatter);
        List<AwardCouponDTO> list = awardCouponMapper.selectProcess(activityId,formattedDate);
        List<AwardCouponDTO> couponAwardList = new ArrayList<>();
        for (AwardCouponDTO couponAwardDTO : list) {
            couponAwardDTO.setCurrentPeriodTimes(awardCouponMapper.selectCount(activityId,couponAwardDTO.getCouponId(),formattedDate));
            couponAwardList.add(couponAwardDTO);
        }
        return couponAwardList;
    }

    /**
     * 根据活动ID查询卡券活动信息表
     * @return
     */
    public List<AwardCouponDTO> selectjh(Long activityId) {
        return awardCouponMapper.selectjh(activityId);
    }

    /**
     * 获取可激活卡券列表
     * @param iPage
     * @param couponId
     * @param radius
     * @return
     */
    public IPage<AgentDestroyVO> getAgentDestroyList(IPage iPage, PointDTO location, Long couponId, String radius) {
        AwardCouponEntity awardCouponEntity = baseMapper.selectById(couponId);
        AwardSettingEntity awardSettingEntity = awardSettingService.getOne(AwardSettingEntity.gw().eq(AwardSettingEntity::getAwardId, couponId)
                .eq(AwardSettingEntity::getAwardType, Constants.AWARD.COUPON));
        // 是否限制可派发/激活机构 0否，1是
        if (awardSettingEntity.getIsAllocation().equals(0)) {
            List<String> agentNos = agentInfoService.queryAllSubAgentNo(awardCouponEntity.getAgentNo());
            if (agentNos.isEmpty()) {
                return null;
            }
            return agentInfoService.getNearAgentList(iPage, location, radius, agentNos);
        }
        return agentInfoService.getCouponAgentDestroyList(iPage,location,couponId,radius);
    }

    public void sendToMchUser(Long activityId,Long agentUserId,Long userId,Long fansId,JSONObject receiptContent,String appId,Long agentFansId) {
        FansUserEntity userEntity = fansUserService.getById(userId);
        if(0 == userEntity.getIsLogin() && 0== userEntity.getIsFollow()){
            throw new BizException(ApiCodeEnum.LITE_USER_INFO_ERROR, "请先到小程序中进行登录注册，并关注活动公众号，再进行参与！");
        }
        //        检测用户信息
        FansEntity fansEntity = fansService.getById(userEntity.getFansId());
        if (userEntity == null || StringUtils.isEmpty(userEntity.getOpenId()) || StringUtils.isEmpty(fansEntity.getPhone())) {
            throw new BizException("请客户完善个人信息并关注活动公众号");
        }

        JSONObject json = new JSONObject();
        FansUserEntity agentUser = fansUserService.getById(agentUserId);
        if(null == agentUser){
            throw new BizException("人员信息不存在，请核实");
        }else{
            json.put("agentUserId",agentUserId);
//            json.put("agentNo",agentUser.getAgentNo());
        }
        //添加回执信息
        if (ObjectUtils.isNotEmpty(receiptContent)){
            json.put("receiptContent",JSONUtil.toJsonStr(receiptContent));
        }

        if(Objects.isNull(activityId) ||  Objects.isNull(userId) || Objects.isNull(fansId)){
           throw new BizException("网络故障，请稍后重试！");
        }
        fansActivityService.addRecord(fansId, appId,activityId,null);
        log.info("扫码派券接口调用：【活动id：{}，用户id：{}，fansId：{}】",activityId,userId,fansId);
        ActivityEntity activityEntity = activityService.getById(activityId);

        List<ActivityAwardAndSettingBo> awardAndSetting = activityAwardService.getAwardAndSetting(activityId);

        // 查询卡券配置活动信息及app信息
        for (ActivityAwardAndSettingBo activityAwardAndSettingBo : awardAndSetting){
            if (ObjectUtils.isEmpty(activityAwardAndSettingBo)) {
                throw new BizException("该奖品未配置活动");
            }
            // 校验同主体发券是否参数完整
            sendAwardService.checkActivitySubject(fansId, activityAwardAndSettingBo);
        }
        FansActivityDTO fansActivityDTO = new FansActivityDTO();
        BeanUtils.copyProperties(activityEntity, fansActivityDTO);
        fansActivityDTO.setActivityId(activityId);
        fansActivityDTO.setAppId(appId);
        fansActivityDTO.setFansId(fansId);
        FansAgentEntity fansAgentEntity = fansAgentService.lambdaQuery().eq(FansAgentEntity::getFansId, agentFansId).eq(FansAgentEntity::getAppId, appId).eq(FansAgentEntity::getIsDeleted, 0).one();
        if(ObjectUtils.isEmpty(fansAgentEntity)){
            throw new BizException("未绑定机构派券权限");
        }
        AgentEmployeeEntity agentEmployee = agentEmployeeService.getById(fansAgentEntity.getAgentEmployeeId());
        if(ObjectUtils.isEmpty(agentEmployee)){
            throw new BizException("未绑定机构派券权限");
        }
        fansActivityDTO.setAgentNo(agentEmployee.getAgentNo());

        BaseActivityService activityService = SpringBeansUtil.getBean(activityEntity.getActivityTemplateNo() + "Service", BaseActivityService.class);
        fansActivityDTO.setAgentFansId(agentFansId);
        activityService.takePartIn(fansActivityDTO);
    }

    public IPage<ExportAwardVO> activityCouponDetail(IPage iPage , ActivityAwardDTO activityAwardDTO) {
        return baseMapper.activityCouponDetail(iPage,activityAwardDTO);
    }
    public List<ExportAwardVO> activityCouponDetail(ActivityAwardDTO activityAwardDTO) {
        return baseMapper.activityCouponDetail(activityAwardDTO);
    }
//    public ExportAwardVO activityCouponNum(ActivityAwardDTO activityAwardDTO) {
//        return baseMapper.activityCouponNum(activityAwardDTO);
//    }
}
